//
//  ShareKit.m
//  Share
//
//  Created by CPX on 2018/10/15.
//  Copyright © 2018年 CPX. All rights reserved.
//

#import "ShareKit.h"
#import "UIViewController+ShareKitHelper.h"
#import "UIImage+ShareKitHelper.h"
#import "FBSDKShareKit.h"
#import "TwitterKit/TWTRKit.h"
#import "LoginKit.h"

#import <Photos/Photos.h>

NSErrorDomain ShareErrorDomain = @"sharekit.error";

/**
 分享组件
 @author yzl
 */
@interface ShareKit()<UIImagePickerControllerDelegate,UINavigationControllerDelegate,FBSDKSharingDelegate,TWTRComposerViewControllerDelegate>

@property (nonatomic,strong) ShareCompletion completion;
@property (nonatomic, copy) NSString *link;
@property (nonatomic) ShareType type;

@property (nonatomic, strong) ShareItem *item;

@end

@implementation ShareKit

+ (instancetype)sharedKit{
    static dispatch_once_t onceToken;
    static ShareKit *kit = nil;
    dispatch_once(&onceToken, ^{
        kit = [ShareKit new];
    });
    return kit;
}

+ (void)requestAuthorizationWithCompletion:(void (^)(NSError*))completion{
    [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            switch (status) {
                case PHAuthorizationStatusAuthorized: {
                    
                    completion(nil);
                    
                    break;
                }
                    
                case PHAuthorizationStatusDenied: {
                    
                    NSError *error = [NSError errorWithDomain:ShareErrorDomain code:-9999 userInfo:@{NSLocalizedDescriptionKey:@"Authorization Status Denied"}];
                    completion(error);
                    
                    break;
                }
                    
                case PHAuthorizationStatusRestricted: {
                    NSError *error = [NSError errorWithDomain:ShareErrorDomain code:-9999 userInfo:@{NSLocalizedDescriptionKey:@"Authorization Status Restricted"}];
                    completion(error);
                    break;
                }
                    
                default:
                    break;
            }
        });
    }];
}

+ (void)shareWithType:(ShareType)type item:(ShareItem *)item completion:(ShareCompletion)completion{
    if (type == kShareTypeFB) {
        if (item.type == kShareItemTypeText || item.type == kShareItemTypeLink) {
            [self shareFBLink:item completion:completion];
        }
        else if (item.type == kShareItemTypeImage){
            [self shareFBImage:item completion:completion];
        }
        else if (item.type == kShareItemTypePhoto){
            [self shareFBPhoto:item completion:completion];
        }
    }
    else if (type == kShareTypeTwitter){
        TWTRAPIClient *client = [TWTRAPIClient clientWithCurrentUser];
        if (!client.userID.length) {
//            NSError *error = [NSError errorWithDomain:ShareErrorDomain code:-9999 userInfo:@{NSLocalizedDescriptionKey:@"Not Login"}];
//            completion(error,NO);
            [LoginKit TwitterLoginWithSuccess:^(LoginResult * _Nonnull result) {
                
            } error:^(NSError * _Nullable error) {
                
            }];
            return;
        }
        if (item.type == kShareItemTypeText ) {
            [self shareTwitterText:item completion:completion];
        }
        else if (item.type == kShareItemTypeLink){
            [self shareTwitterLink:item completion:completion];
        }
        else if (item.type == kShareItemTypeImage){
            [self shareTwitterImage:item completion:completion];
        }
        else if (item.type == kShareItemTypePhoto){
            [self shareTwitterPhoto:item completion:completion];
        }
    }
}

+ (void)shareFBLink:(ShareItem*)item completion:(ShareCompletion)completion{
    FBSDKShareLinkContent *content = [[FBSDKShareLinkContent alloc] init];
    content.quote = item.text;
    if (item.link) {
        content.contentURL = [NSURL URLWithString:item.link];
    }
    [FBSDKShareDialog showFromViewController:[UIViewController currentViewController] withContent:content delegate:[ShareKit sharedKit]];
    [ShareKit sharedKit].completion = completion;
}

+ (void)shareFBImage:(ShareItem*)item completion:(ShareCompletion)completion{
    FBSDKSharePhotoContent *content = [FBSDKSharePhotoContent new];
    FBSDKSharePhoto *p = [FBSDKSharePhoto photoWithImage:item.image userGenerated:YES];
    content.photos = @[p];
    if (item.link) {
//        content.contentURL = [NSURL URLWithString:item.link];
    }
    [FBSDKShareDialog showFromViewController:[UIViewController currentViewController] withContent:content delegate:[ShareKit sharedKit]];
    [ShareKit sharedKit].completion = completion;
}

+ (void)shareFBPhoto:(ShareItem*)item completion:(ShareCompletion)completion{
    UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
    imagePickerController.delegate = [ShareKit sharedKit]; //设置代理
    imagePickerController.allowsEditing = NO;
    imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    
    [[UIViewController currentViewController] presentViewController:imagePickerController animated:YES completion:nil];
    [ShareKit sharedKit].completion = completion;
    [ShareKit sharedKit].type = kShareTypeFB;
    [ShareKit sharedKit].item = item;
}

+ (void)shareTwitterText:(ShareItem*)item completion:(ShareCompletion)completion{
    NSString *t = item.text;
    
    TWTRComposerViewController *ctr = [[TWTRComposerViewController alloc] initWithInitialText:t image:nil videoURL:nil];
    [[UIViewController currentViewController] presentViewController:ctr animated:YES completion:nil];
}

+ (void)shareTwitterLink:(ShareItem*)item completion:(ShareCompletion)completion{
    NSString *t = item.text;
    if (item.link) {
        t = [item.text stringByAppendingFormat:@"\n%@",item.link];
    }
    TWTRComposerViewController *ctr = [[TWTRComposerViewController alloc] initWithInitialText:t image:nil videoURL:nil];
    [[UIViewController currentViewController] presentViewController:ctr animated:YES completion:nil];
}

+ (void)shareTwitterImage:(ShareItem*)item completion:(ShareCompletion)completion{
    TWTRComposerViewController *ctr = [[TWTRComposerViewController alloc] initWithInitialText:item.text image:item.image videoURL:nil];
    ctr.delegate = [ShareKit sharedKit];
    [[UIViewController currentViewController] presentViewController:ctr animated:YES completion:nil];
    [ShareKit sharedKit].completion = completion;
}

+ (void)shareTwitterPhoto:(ShareItem*)item completion:(ShareCompletion)completion{
    UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
    imagePickerController.delegate = [ShareKit sharedKit]; //设置代理
    imagePickerController.allowsEditing = NO;
    imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    
    [[UIViewController currentViewController] presentViewController:imagePickerController animated:YES completion:nil];
    [ShareKit sharedKit].completion = completion;
    [ShareKit sharedKit].type = kShareTypeTwitter;
    [ShareKit sharedKit].item = item;
}

#pragma mark - image picker view

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    UIImage *image = info[@"UIImagePickerControllerOriginalImage"];
    NSInteger length = 1024*500;
    //默认500KB限制
    image = [image compressWithMaxLength:length];
    [ShareKit sharedKit].item.image = image;
    [picker dismissViewControllerAnimated:YES completion:^{
        
        if (self.type == kShareTypeFB) {
            [ShareKit shareFBImage:[ShareKit sharedKit].item completion:[ShareKit sharedKit].completion];
        }
        else if (self.type == kShareTypeTwitter){
            [ShareKit shareTwitterImage:[ShareKit sharedKit].item completion:[ShareKit sharedKit].completion];
        }
    }];
}


#pragma mark - FB

- (void)sharer:(id<FBSDKSharing>)sharer didCompleteWithResults:(NSDictionary *)results{
    self.completion(nil,NO);
    self.completion = nil;
}

- (void)sharer:(id<FBSDKSharing>)sharer didFailWithError:(NSError *)error{
    self.completion(error,NO);
    self.completion = nil;
}

- (void)sharerDidCancel:(id<FBSDKSharing>)sharer{
    self.completion(nil,YES);
    self.completion = nil;
}

#pragma mark - twitter

- (void)composerDidCancel:(TWTRComposerViewController *)controller{
    self.completion(nil,YES);
    self.completion = nil;
}

- (void)composerDidSucceed:(TWTRComposerViewController *)controller withTweet:(TWTRTweet *)tweet{
    self.completion(nil,NO);
    self.completion = nil;
}

- (void)composerDidFail:(TWTRComposerViewController *)controller withError:(NSError *)error{
    self.completion(error,NO);
    self.completion = nil;
}


@end
